import { WS_EVENTS } from '@app-cad/common/Constants';
import CommonReloadModal from '@app-cad/common/components/CommonReloadModal';
import { userEvents } from '@app-cad/module';

import { useCallback, useEffect, useState } from 'react';

export default function ReloadModal() {
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  useEffect(() => {
    registerEvents();
    return () => {
      unRegisterEvents();
    };
  }, []);
  const listen = useCallback((status) => {
    setOpen(status);
  }, []);

  const registerEvents = () => {
    userEvents.on(WS_EVENTS.WS_LOSE_EVENT, listen);
  };
  const unRegisterEvents = () => {
    userEvents.off(WS_EVENTS.WS_LOSE_EVENT, listen);
  };
  const backHome = () => {
    window.location.replace('/projects');
  };
  const reloadPage = () => {
    setLoading(true);
    window.setTimeout(() => {
      window.location.reload();
      setLoading(false);
      setOpen(false);
    }, 1000);
  };
  return (
    <CommonReloadModal
      reloadPage={reloadPage}
      backHome={backHome}
      open={open}
      loading={loading}
      message='连接超时，请返回主页或刷新页面'
    />
  );
}
